var friends = new Array();

function getData() {
    document.getElementById('message').innerHTML = 'Loading..Please Wait...';

    var params = {};
    params[opensocial.DataRequest.PeopleRequestFields.MAX] = 1000;

    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), 'viewer');
    req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, params), 'viewerFriends');
    req.send(onLoadFriends);
}

function createProfileURL(person) {
    return gadgets.util.getUrlParameters()["parent"] + '/Main#' + person.getField(opensocial.Person.Field.PROFILE_URL)
}

function showPersonDetails(person) {
    var html = '<div class="thumbbox"><div class="thumb"><center><a target="_blank" href="' + createProfileURL(person) + '"><img src="' + person.getField(opensocial.Person.Field.THUMBNAIL_URL) + '"/></a></center></div><p class="uname"><a target="_blank" href="' + createProfileURL(person) + '">' + person.getDisplayName() + '</a></p></div>'
    appendHtml(html);
}

function appendHtml(html){
    var mainDiv = document.getElementById('message');
    mainDiv.innerHTML += html;
}

function onLoadFriends(dataResponse) {
    document.getElementById('message').innerHTML = '';

    var viewerFriends = dataResponse.get('viewerFriends').getData();
    viewerFriends.each(function(person) {
        friends.push(person);
    });

    var params = {};
    params[opensocial.DataRequest.PeopleRequestFields.MAX] = 1000;

    alert('Getting: '+friends[0].getField(opensocial.Person.Field.ID));
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPeopleRequest(friends[0].getField(opensocial.Person.Field.ID), params), 'friendsOfFriends');
    req.send(onLoadFriendsOfFriends);


    for (var i = 0; i < friends.length; i++) {
        showPersonDetails(friends[i]);
    }
}

function onLoadFriendsOfFriends(){
    var viewerFriends = dataResponse.get('friendsOfFriends').getData();
    alert("Friends Count: "+viewerFriends.length);
}

gadgets.util.registerOnLoadHandler(getData);
